<template>
  <el-form label-position="right" label-width="100" :model="skuData">
    <el-form-item label="sku名称" prop="skuName">
      <el-input
        placeholder="请输入sku名称"
        v-model="skuData.skuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="价格（元）" prop="price">
      <el-input
        type="number"
        placeholder="价格"
        v-model.number="skuData.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量（g）" prop="weight">
      <el-input
        type="number"
        placeholder="重量（g）"
        v-model.number="skuData.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="sku描述" prop="skuDesc">
      <el-input
        type="textarea"
        placeholder="sku描述"
        v-model="skuData.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttr">
      <el-form inline>
        <el-form-item
          :label="item.attrName"
          v-for="item in attrList"
          :key="item.id"
        >
          <el-select
            v-model="item.attrIdAndValueId"
            fit-input-width
            style="min-width: 200px"
          >
            <el-option
              :value="`${item.id}-${attr.id}`"
              :label="attr.valueName"
              v-for="attr in item.attrValueList"
              :key="attr.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttr">
      <el-form inline>
        <el-form-item
          :label="item.saleAttrName"
          v-for="item in skuSaleAttrList"
          :key="item.id"
        >
          <el-select
            v-model="item.saleAttrIdAndValueId"
            fit-input-width
            style="min-width: 200px"
          >
            <el-option
              :value="`${item.id}-${attr.id}`"
              :label="attr.saleAttrValueName"
              v-for="attr in item.spuSaleAttrValueList"
              :key="attr.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="sku图片" prop="skuImageList">
      <el-table border :data="spuImageList" ref="skuImageTableRef">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="图片" prop="skuImage">
          <template #default="{ row }">
            <el-image
              :src="row.imgUrl"
              style="width: 100px; height: 100px"
              fit="fill"
              :preview-src-list="[row.skuImage]"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              title="设置默认"
              @click="setDefaultImage(row)"
            >
              设置默认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveSku">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts" name="skuForm">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { reqGetAttr } from '@/api/product/attr/index.ts'
import {
  reqGetSpuSaleAttrList,
  reqGetSpuImageList,
  reqAddSku,
} from '@/api/product/spu'
import useCategoryStore from '@/store/modules/category.ts'
import type { SpuInfo, SkuData } from '@/api/product/spu/type.ts'
const categoryStore = useCategoryStore()
let $emit = defineEmits(['changeScene'])
//取消
const cancle = () => {
  $emit('changeScene', { flag: 0, id: '' })
}
let attrList = ref<any>([])
let skuSaleAttrList = ref<any>([])
let spuImageList = ref<any>([])

//收集sku的参数
let skuData = ref<SkuData>({
  category3Id: '',
  spuId: '',
  tmId: '',
  skuName: '',
  price: 0,
  weight: 0,
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: '',
})

const initSkuData = async (row: SpuInfo) => {
  console.log('初始化sku需要的数据')
  //获取平台属性
  let res = await reqGetAttr(
    categoryStore.category1Id,
    categoryStore.category2Id,
    categoryStore.category3Id,
  )
  if (res.code === 200) {
    console.log('获取平台属性成功', res.data)
    attrList.value = res.data
  }
  //获取销售属性
  let res2 = await reqGetSpuSaleAttrList(row.id as number)
  if (res2.code === 200) {
    console.log('获取销售属性值成功', res2.data)
    skuSaleAttrList.value = res2.data
  }
  //获取spu图片
  let res3 = await reqGetSpuImageList(row.id as number)
  if (res3.code === 200) {
    console.log('获取图片成功', res3.data)
    spuImageList.value = res3.data
  }
  //收集数据
  skuData.value.spuId = row.id
  skuData.value.category3Id = categoryStore.category3Id
  skuData.value.tmId = row.tmId
}
//设置默认图片
const setDefaultImage = (row: any) => {
  skuData.value.skuDefaultImg = row.imgUrl
  console.log(skuImageTableRef.value)
  // 取消所有选择
  skuImageTableRef.value.clearSelection()
  // 选择当前行
  skuImageTableRef.value.toggleRowSelection(row)
  // skuImageTableRef.value.toggleAllSelection()
}
//保存sku
const saveSku = async () => {
  //组装参数
  //平台属性
  skuData.value.skuAttrValueList = attrList.value.reduce(
    (pre: any, next: any) => {
      if (next.attrIdAndValueId) {
        let [attrId, valueId] = next.attrIdAndValueId.split('-')
        pre.push({
          attrId,
          valueId,
        })
      }
      return pre
    },
    [],
  )
  console.log('收集到的平台属性', skuData.value.skuAttrValueList)
  //销售属性
  skuData.value.skuSaleAttrValueList = skuSaleAttrList.value.reduce(
    (pre: any, next: any) => {
      if (next.saleAttrIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleAttrIdAndValueId.split('-')
        pre.push({
          saleAttrId,
          saleAttrValueId,
        })
      }
      return pre
    },
    [],
  )
  console.log('收集到的销售属性', skuData.value.skuSaleAttrValueList)
  //请求
  const res = await reqAddSku(skuData.value)
  if (res.code === 200) {
    ElMessage.success('添加成功')
    $emit('changeScene', { flag: 0, id: '' })
  } else {
    ElMessage.error('添加失败')
  }
}
const skuImageTableRef = ref()
//
defineExpose({ initSkuData })
</script>

<style scoped lang="scss"></style>
